
package guoan.web.weixin;

import guoan.Exception.RestException;
import guoan.core.common.WebConfig;
import guoan.core.dto.RestResponse;
import guoan.domain.CoachItem;
import guoan.domain.ExamItem;
import guoan.domain.RandomKey;
import guoan.domain.Student;
import guoan.domain.Train;
import guoan.service.CoachService;
import guoan.service.ExamItemService;
import guoan.service.RandomKeyService;
import guoan.service.StudentService;
import guoan.service.TrainService;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * @ClassName: OauthContrller
 * @Description: 通过认证界面进行验证跳转
 * @author Administrator
 * @date 2015年4月21日 下午4:36:50
 * 
 */
@Controller
@RequestMapping("/weixin/student")
public class WeiXinStudentContrller {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private StudentService studentService;
    @Autowired
    private ExamItemService examItemService;
    @Autowired
    private CoachService coachService;
    @Autowired
    private RandomKeyService randomKeyService;

    @Autowired
    private TrainService trianService;

    @RequestMapping(value = "oauthStudent")
    public String oauthStudent(){
        return "/weixin/student/oauthStudent";
    }

    @RequestMapping(value = "examItem", method = RequestMethod.GET)
    public String examItem(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY) == null) {
            return "redirect:/weixin/student/oauthStudent";
        }
        String openid = (String) session
                .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
        List<ExamItem> examItems = examItemService.findByStudentOpenid(openid);
        model.addAttribute("examItems", examItems);
        return "/weixin/student/examItem";
    }

    @RequestMapping(value = "cleanExamItem", method = RequestMethod.GET)
    public String cleanExamItem(Long examItemId, Model model,
            HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY) == null) {
            return "redirect:/weixin/student/oauthStudent";
        }

        Preconditions.checkNotNull(examItemId, "抱歉，参数错误！");

        RestResponse<Boolean> rr = examItemService.cancelExam(examItemId);
        if (rr.getStatus() == 1) {// 正确
            model.addAttribute("msg", "取消成功，将跳转到您的预约信息界面");
            model.addAttribute("url", "/weixin/student/examItem");
            return "/weixin/msg";
        } else {
            model.addAttribute("msg", rr.getMsg());
            model.addAttribute("url", "/weixin/student/examItem");
            return "/weixin/msg";
        }
    }

    @RequestMapping(value = "join", method = RequestMethod.POST)
    public String join(Student student, HttpServletRequest request, Model model){

        if (student == null
                || (student != null && (Strings.isNullOrEmpty(student
                        .getContactNumberF()) || Strings.isNullOrEmpty(student
                        .getStudentName())))) {
            model.addAttribute("msg", "参数错误");
            return "/weixin/msg";
        }
        RestResponse<Boolean> rr = studentService.join(student, request);

        if (rr.getStatus() != 1) {
            model.addAttribute("msg", rr.getMsg());
            return "/weixin/msg";
        } else {
            model.addAttribute("msg", "绑定成功，请等待跳转到预约教练陪练页面");
            model.addAttribute("url", "/weixin/coach/index_1");
            return "/weixin/msg";
        }
    }

    @RequestMapping(value = "updateKey", method = RequestMethod.GET)
    public String updateKey(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        Student student = null;
        if (session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY) != null) {
            String openid = (String) session
                    .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
            student = studentService.findByStudentOpenid(openid);
            if (studentService.findByStudentOpenid(openid) == null) {// 进行学员绑定
                return "redirect:/weixin/student/oauthStudent";
            }
        } else {
            throw new RestException("请在微信中打开");
        }
        List<RandomKey> randomKeys = randomKeyService.findByStudentId(student
                .getId());
        for (RandomKey randomKey : randomKeys) {
            if (randomKey.getCoachType().intValue() == 2) {
                model.addAttribute("randomKeyt", randomKey);
            } else if (randomKey.getCoachType().intValue() == 3) {
                model.addAttribute("randomKeys", randomKey);
            }
        }
        return "/weixin/student/updateKey";
    }

    @RequestMapping(value = "updateKey", method = RequestMethod.POST)
    public String updateKey(String studentKeyt, String studentKeys,
            HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        Student student = null;
        if (session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY) != null) {
            String openid = (String) session
                    .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
            student = studentService.findByStudentOpenid(openid);
            if (studentService.findByStudentOpenid(openid) == null) {// 进行学员绑定
                return "redirect:/weixin/student/oauthStudent";
            }
        } else {
            throw new RestException("请在微信中打开");
        }

        if (Strings.isNullOrEmpty(studentKeyt)) {// 是空的话，清除
            randomKeyService.updateByStudentIdAndCoachType(student.getId(), 2L);
        } else {
            RandomKey randomKey = randomKeyService.findByKey(studentKeyt
                    .toUpperCase());
            if (randomKey == null) {// 不存在
                model.addAttribute("msg", "科目二绑定码[" + studentKeyt
                        + "]不可用，请重新填写");
                return "/weixin/msg";
            }
            // 绑定码变更了
            if (randomKey.getStudentId() == null
                    || !randomKey.getStudentId().equals(student.getId())) {
                if (randomKey.getIsUse().intValue() == 1
                        || randomKey.getCoachType().intValue() != 2) {// 存在，但是不可用
                    model.addAttribute("msg", "科目二绑定码[" + studentKeyt
                            + "]不可用，请重新填写");
                    return "/weixin/msg";
                }
                // 可用的，删除老的，绑定新的
                randomKeyService.updateByStudentIdAndCoachType(student.getId(),
                        2L);
                randomKey.setIsUse(1L);
                randomKey.setStudentId(student.getId());
                randomKeyService.save(randomKey);
            }
        }

        if (Strings.isNullOrEmpty(studentKeys)) {// 是空的话，清除
            randomKeyService.updateByStudentIdAndCoachType(student.getId(), 3L);
        } else {
            RandomKey randomKey = randomKeyService.findByKey(studentKeys
                    .toUpperCase());
            if (randomKey == null) {
                model.addAttribute("msg", "科目三绑定码[" + studentKeys
                        + "]不可用，请重新填写");
                return "/weixin/msg";
            }
            // 绑定码变更了
            if (randomKey.getStudentId() == null
                    || !randomKey.getStudentId().equals(student.getId())) {
                if (randomKey.getIsUse().intValue() == 1
                        || randomKey.getCoachType().intValue() != 3) {// 存在，但是不可用
                    model.addAttribute("msg", "科目三绑定码[" + studentKeys
                            + "]不可用，请重新填写");
                    return "/weixin/msg";
                }
                // 可用的，删除老的，绑定新的
                randomKeyService.updateByStudentIdAndCoachType(student.getId(),
                        3L);
                randomKey.setIsUse(1L);
                randomKey.setStudentId(student.getId());
                randomKeyService.save(randomKey);
            }
        }
        model.addAttribute("msg", "绑定码修改成功");
        model.addAttribute("url", "/weixin/student/updateKey");
        return "/weixin/msg";
    }

    @RequestMapping(value = "userCoach", method = RequestMethod.GET)
    public String userCoach(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        Student student = null;
        if (session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY) != null) {
            String openid = (String) session
                    .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
            student = studentService.findByStudentOpenid(openid);
            if (studentService.findByStudentOpenid(openid) == null) {// 进行学员绑定
                return "redirect:/weixin/student/oauthStudent";
            }
        } else {
            throw new RestException("请在微信中打开");
        }

        List<CoachItem> coachItems = coachService
                .findCoachItemByStudentId(student.getId());
        model.addAttribute("coachItems", coachItems);
        return "/weixin/student/userCoach";
    }

    /**
     * 学员取消自己的预约,可以取消当天的预约,任何情况下都可以,这他妈的合理吗?
     * 
     * @param coachItemId
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "cleanCoachItem", method = RequestMethod.GET)
    public String cleanCoachItem(Long coachItemId, Model model,
            HttpServletRequest request){
        HttpSession session = request.getSession();
        Student student = null;
        if (session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY) != null) {
            String openid = (String) session
                    .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
            student = studentService.findByStudentOpenid(openid);
            if (studentService.findByStudentOpenid(openid) == null) {// 进行学员绑定
                return "redirect:/weixin/student/oauthStudent";
            }
        } else {
            throw new RestException("请在微信中打开");
        }
        Preconditions.checkNotNull(coachItemId, "抱歉，参数错误！");
        CoachItem coachItem = coachService.findCoachItem(coachItemId,
                student.getId());
        if (coachItem == null) {
            throw new RestException("参数错误");
        }
        // 判断选择的时间段是否大于当前时间 yyyy-MM-dd hh:mm
        DateTime nowTime = new DateTime(new DateTime().getYear(),
                new DateTime().getMonthOfYear(),
                new DateTime().getDayOfMonth(), 0, 0, 0);
        DateTime coachTime = coachItem.getExamTime();
        DateTime temTime = new DateTime(coachTime.getYear(),
                coachTime.getMonthOfYear(), coachTime.getDayOfMonth(), 0, 0, 0);
        if (nowTime.isAfter(temTime.getMillis())) {// 您所选中的练车时间比现在早，不运行选择
            model.addAttribute("msg", "您不能取消前一天的预约，请重新选择");
            model.addAttribute("url", "/weixin/student/userCoach");
            return "/weixin/msg";
        } else {
            coachService.cleanItemCoach(coachItemId);
        }

        model.addAttribute("msg", "预约取消成功");
        model.addAttribute("url", "/weixin/student/userCoach");
        return "/weixin/msg";
    }

    @RequestMapping(value = "myTrain", method = RequestMethod.GET)
    public String myTrain(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        Student student = null;
        if (session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY) != null) {
            String openid = (String) session
                    .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
            student = studentService.findByStudentOpenid(openid);
            if (studentService.findByStudentOpenid(openid) == null) {// 进行学员绑定
                return "redirect:/weixin/student/oauthStudent";
            }
        } else {
            throw new RestException("请在微信中打开");
        }

        List<RandomKey> rks = randomKeyService.findByStudentId(student.getId());
        for (RandomKey rk : rks) {
            Train train = trianService.findOne(rk.getTrainId());
            rk.setTrain(train);
        }

        model.addAttribute("rks", rks);
        return "/weixin/student/myTrain";
    }
}
